package cn.yunhe.controller;

import cn.yunhe.entity.Department;
import cn.yunhe.entity.Role;
import cn.yunhe.entity.User;
import cn.yunhe.service.MenuItemService;
import cn.yunhe.service.RoleService;
import cn.yunhe.service.impl.UserServiceImpl;
import cn.yunhe.util.ListToUserUtil;
import cn.yunhe.util.MultipartFileToFile;
import cn.yunhe.util.ReadExcel;
import com.github.pagehelper.Page;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class UserController {

    @Resource
    private UserServiceImpl userService;
    @Resource
    private MenuItemService menuItemService;
    @Resource
    private RoleService roleService;

    @RequestMapping("/toAddUser")
    public ModelAndView toAdd(Role role){
        ModelAndView mv = new ModelAndView("/add-user");
        mv.addObject("roleId",role.getId());
        return mv;
    }

    @RequestMapping("addUser")
    public String addUser(User user, Department department, Integer roleId, HttpSession session) {
        user.setDepartment(department);
        String pwd = user.getPassword();
        user.setPassword(new SimpleHash("MD5", pwd, user.getUserName()).toString());
        Timestamp creatTime = new Timestamp(new Date().getTime());
        User curr = (User) session.getAttribute("Curr_User");
        user.setCreateBy(curr.getUserId());
        user.setCreateTime(creatTime);
        Map map = new HashMap();
        map.put("user", user);
        map.put("roleId", roleId);
        int c1 = userService.addUser(map);
        int c2 = userService.addUser2Role(map);
        if (c1 > 0 && c2 > 0) {
            return "success";
        } else {
            return "failed";
        }
    }

    @RequestMapping("getUserByName")
    public User getUserByName(String username){
        User user =userService.getUserByName(username);
        if(user != null){
            return user;
        }
        return null;
    }

    @RequestMapping("userLogin")
    public void userLogin(HttpSession httpSession, HttpServletResponse response, User user) throws IOException {
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUserName(), user.getPassword(), false);//把账户和密码存到令牌中
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        //if (!currentUser.isAuthenticated()) {
        try {
            subject.login(usernamePasswordToken);//进行认证
        } catch (Exception e) {
            System.out.println("密码错误");
            session.removeAttribute("user");
            session.setAttribute("message", "账户或密码错误");
            response.sendRedirect("/login.html");
        }
        //}
        User user1 = (User) session.getAttribute("user");
        //存储user对象
        if(user1 != null){
            User user2 = userService.getUserById(user1.getUserId());
            httpSession.setAttribute("Curr_User", user2);//用户存到session中
            System.out.println("---------登录成功---------");
            response.sendRedirect("/view/main.html");
        }
    }

    @RequestMapping("/userLogout")
    public void userLogout(HttpServletResponse response) throws IOException {
        System.out.println("--------注销--------");
        response.sendRedirect("/login.html");
    }

    @RequestMapping("getAllUserByPage")
    public Map getAllUserByPage(int pageSize, int currPage, User user, Department department, int role) {
        user.setDepartment(department);
        Map<String, Object> map = new HashMap<>();
        map.put("pageSize", pageSize);
        map.put("currPage", currPage);
        map.put("user", user);
        map.put("role", role);
        Page page = userService.getUserByPage(map);
        map.put("page", page);
        map.put("totalPage", page.getPages());
        return map;
    }

    @RequiresPermissions("/view/user-list.html")
    @RequestMapping("/toStudentList.do")
    public void toStudentList(HttpServletResponse response) throws IOException {
        response.sendRedirect("/view/user-list.html");
    }
    @RequiresPermissions("/view/teacher-list.html")
    @RequestMapping("/toTeacherList.do")
    public void toTeacherList(HttpServletResponse response) throws IOException {
        response.sendRedirect("/view/teacher-list.html");
    }
    @RequiresPermissions("/view/admin-list.html")
    @RequestMapping("/toAdminList.do")
    public void toAdminList(HttpServletResponse response) throws IOException {
        response.sendRedirect("/view/admin-list.html");
    }

    @RequestMapping("editPwd")
    public ModelAndView editPwd(String userId) {
        if (userId != null){
            int id = Integer.parseInt(userId);
            ModelAndView mv = new ModelAndView("edit-password");
            mv.addObject("user", userService.getUserById(id));
            return mv;
        }
        return null;
    }

    @RequestMapping("updUserPwd")
    public int updUserPwd(User user) {
        if(user.getPassword()!=null){
            int x = userService.updUserPwd(user);
            return x;
        }else {
            return 0;
        }

    }

    @RequestMapping("editInfo")
    public ModelAndView editInfo(HttpServletRequest request, int userId) {
        ModelAndView mv = new ModelAndView("editUserInfo");
        User user = userService.getUserById(userId);
        user.setUserId(userId);
        request.setAttribute("user", user);
        return mv;
    }

    @RequestMapping("doEdit")
    public int doEdit(User user, Department department) {
        user.setDepartment(department);
        return userService.updUserInfo(user);
    }

    @RequestMapping("doDisable")
    public int doDisable(int userId) {
        return userService.updUserIsDisable(userId);
    }

    @RequestMapping("toFileUploadUser")
    public ModelAndView toFileUploadUser() {
        return new ModelAndView("users-import");
    }

    @RequestMapping("fileUploadUser")
    public String fileUploadUser(@RequestParam("fileName") MultipartFile file, HttpSession session) throws IOException {
        if (file.isEmpty()) {
            return "文件不能为空";
        }
        List<List<String>> lists = ReadExcel.readExcel(MultipartFileToFile.translateUser(file));
        for (List<String> list : lists) {
            ListToUserUtil listToUserUtil = new ListToUserUtil();
            Map map = new HashMap();
            User u = listToUserUtil.getUser(list, session);
            map.put("user", u);
            map.put("roleId", 3);
            userService.addUser(map);
            userService.addUser2Role(map);
        }
        return "成功";
    }

    @RequestMapping("/getStudentCount")
    public int getStudentCount() {
        return userService.studentCount();
    }

    @RequiresPermissions("/view/user-list.html")
    @RequestMapping("/toUser.do")
    public void toUser(HttpServletResponse response) throws IOException {
        response.sendRedirect("/view/user-list.html");
    }

    @RequiresPermissions("/view/main.html")
    @RequestMapping("/toMain.do")
    public void toMain(HttpServletResponse response) throws IOException {
        response.sendRedirect("/view/main.html");
    }

    public UserServiceImpl getUserService() {
        return userService;
    }

    public void setUserService(UserServiceImpl userService) {
        this.userService = userService;
    }

    public MenuItemService getMenuItemService() {
        return menuItemService;
    }

    public void setMenuItemService(MenuItemService menuItemService) {
        this.menuItemService = menuItemService;
    }

    public RoleService getRoleService() {
        return roleService;
    }

    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }
}
